package com.yanyu.space.common.im.handler;

import com.alibaba.fastjson.JSONObject;
import com.yanyu.space.common.core.exception.ServiceException;
import com.yanyu.space.common.im.session.SessionFactory;
import com.yanyu.space.common.im.support.ImRecer;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;

import java.util.List;

/**
 * @author yanyu
 */
@Slf4j
@AllArgsConstructor
public class WebSocketFrameHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    private List<ImRecer> imRecers;

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        ctx.fireChannelActive();
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame frame) throws Exception {
        String text = frame.text();
        if(CollectionUtils.isNotEmpty(imRecers)) {
            JSONObject jsonObject = JSONObject.parseObject(text);
            if(!jsonObject.containsKey("username")) {
                log.error("没有包含用户名 -> {}", text);
                throw new ServiceException();
            }
            SessionFactory.getSession().bind(ctx.channel(), jsonObject.getString("username"));
            imRecers.parallelStream().forEach(imRecer -> {
                imRecer.handleMessage(ctx, text);
            });

        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.error("发生异常", cause);
        SessionFactory.getSession().unbind(ctx.channel());
        //关闭连接
        ctx.close();
    }
}
